/**
 * Copyright 2013 Matt Holland <code.monkey.ota at gmail.com>
 *
 * This file is part of BotTender.
 *
 * BotTender is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BotTender is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with BotTender. If not, see <http://www.gnu.org/licenses/>.
 */

package ota.ircbot.bottender.admin;

import java.util.Hashtable;

import org.pircbotx.User;


// Authorized users

public abstract class Authorized {
	
	//Store the User object as the value, using the member name as key
	private static Hashtable<String, User> users = new Hashtable<String, User>(); // Converted to lowercase
	private static User owner; // This will be the Owner's user object, in order to add an extra level of auth
	private static Boolean notice = false; // If true, the bot will notify the owner of any failed attempt
	// to modify the list. IE: A user tries to add someone to the list that is not the owner.
	
	
	public static void setOwner(User ownOb) { // This will be set to the owner specified on startup
		if(ownOb != null) owner = ownOb;
	}
	
	public static void addAuth(User aUser, User caller) { // This will add a user to the AuthList
		if(aUser != null) { // It will require the owner to execute
			if (isOwner(caller)) {
				users.put(aUser.getNick().toLowerCase(), aUser);
			}
			else { 
				caller.sendMessage("Sorry, " +caller.getNick()+ " " +owner.getNick()+ " needs to execute this command.");
				if(notice) owner.getBot().sendNotice(owner, caller.getNick()+ " has attempted to authorize " +aUser.getNick()+".");
			} // end else
		} // End if
	}
	
	public static void delAuth(User aUser, User caller) {
		if(isOwner(caller)) {
			users.remove(aUser.getNick());
		}
		else {
			caller.sendMessage("Sorry, " +caller.getNick()+ " " +owner.getNick()+ " needs to execute this command.");
			if(notice) owner.getBot().sendNotice(owner, caller.getNick()+ " has attempted to remove " +aUser.getNick()+"'s authorization.");
		}
	}
	
	public static Boolean isAuthed(User aUser) {
		// First check if the user is on the list, if so, check that their user objects match
		if((users.containsKey(aUser.getNick().toLowerCase()) && users.get(aUser.getNick()).canEqual(aUser)) || aUser.canEqual(owner)) {
			return true; // if both are true, OR the user is the owner, return true
		}
		return false; // Otherwise, fail
	}
	
	public static Boolean isOwner(User aUser) {
		if(aUser.canEqual(owner)) return true;
		
		return false;
	}

}
